<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>用户管理</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../../res/layui/css/layui.css"  media="all">
  <link rel="stylesheet" href="../../res/css/common/font-awesome.min.css" media="all">
  <link rel="stylesheet" href="../../res/layui-config/css/app.css" media="all">
  <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>
	<!-- <input type="checkbox" name="" title="管理员">
      						<input type="checkbox" name="" title="专职人员">
      						<input type="checkbox" name="" title="销售部管理员">
							<input type="checkbox" name="" title="质检人员">
      						<input type="checkbox" name="" title="采购部管理员">
      						<input type="checkbox" name="" title="生产部管理员">
							<input type="checkbox" name="" title="总店总经理">
      						<input type="checkbox" name="" title="分公司总经理"> -->
	<div class="kit-table">
		<form class="layui-form" lay-filter="kit-search-form">
			<!-- 左上角的两个按钮 -->
		    <div class="kit-table-header">
		        <div class="kit-search-btns">
		            <a href="javascript:;" data-action="add" class="layui-btn layui-btn-sm"><i class="layui-icon">&#xe608;</i> 新增</a>
		            <a href="javascript:;" data-action="del-bulk" class="layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon">&#xe640;</i> 批量删除</a>
		        </div>
		        <div class="kit-search-inputs">
		            <div class="kit-search-keyword">
		                <input type="text" class="layui-input" id="serach-one" placeholder="请输入用户名.." onKeyUp="lockInput(this,'serach-two')"/>
		                <button lay-submit lay-filter="search"><i class="layui-icon">&#xe615;</i></button>
		            </div>
		            <div class="kit-search-more" id="kit-search-more">更多筛选<i class="layui-icon">&#xe61a;</i></div>
		        </div>
		    </div>
		    <!-- 搜索扩展工具条 -->
	        <div class="kit-search-mored layui-anim layui-anim-upbit">
	            <div class="kit-search-body">
	                <div class="layui-form-item">
	                    <label class="layui-form-label">用户名</label>
	                    <div class="layui-input-block">
	                        <input type="text" name="adminName" id="serach-two" placeholder="请输入用户名" autocomplete="off" class="layui-input" onKeyUp="lockInput(this,'serach-one')">
	                    </div>
	                </div>
	                <div class="layui-form-item">
	                    <label class="layui-form-label">公司名称</label>
	                    <div class="layui-input-block">
	                        <input type="text" name="comId" id="serach-two" placeholder="请输入公司名称" autocomplete="off" class="layui-input" onKeyUp="lockInput(this,'serach-one')">
	                    </div>
	                </div>
	            </div>
	            <div class="kit-search-footer">
	                <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary kit-btn reset-btn">重置</button>
	                <button lay-submit lay-filter="search" class="layui-btn layui-btn-sm kit-btn">确定</button>
	            </div>
	        </div>
		</form>
		
		<!-- 操作按钮 -->
		<div class="kit-table-body">
			<table id="demo" lay-filter="demo"></table>
			<script type="text/html" id="barDemo">
				<a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
				<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
			</script>
		</div>
	</div> 
		<!-- 修改页面 -->
		<script type="text/html" id="edit-tpl">
		   	<div style="margin:10px">
		        <form class="layui-form" action="" lay-filter="form-edit">
		            <input type="hidden" name="adminId" value="{{d.rowdata.adminId}}" />
					<input type="hidden" name="drugPictrue" value="{{d.rowdata.adminPictrue}}" >
					<input type="hidden" id="roid" name="roId" style="width:700px;"/>
					<div class="layui-form-item">
		                <label class="layui-form-label">公司名称</label>
		                <div class="layui-input-block">
		                    <select name="comId" lay-verify="required">
		                      <option value=""></option>
		                      {{# layui.each(d.types,function(index,item){ }}                      
		                      {{# if(item.comId===d.rowdata.comId){}}
		                      <option value="{{item.comId}}" selected>{{item.comName}}</option>
		                      {{#}else{}}
		                      <option value="{{item.comId}}">{{item.comName}}</option>
		                      {{#};}}
		                      {{# });}}
		                    </select>
		                </div>
		            </div>
		            <div class="layui-form-item">
		                <label class="layui-form-label">用户名</label>
		                <div class="layui-input-block">
		                    <input type="text" name="adminName" required lay-verify="required" value="{{d.rowdata.adminName}}" placeholder="请输入用户名" autocomplete="off" class="layui-input">
		                </div>
		            </div>
					<div class="layui-form-item">
		                <label class="layui-form-label">密码</label>
		                <div class="layui-input-block">
		                    <input type="password" name="adminPwd" required lay-verify="required" value="{{d.rowdata.adminPwd}}" placeholder="请输入密码" autocomplete="off" class="layui-input">
		                </div>
		            </div>
					<div class="layui-form-item">
		                <label class="layui-form-label">角色描述</label>
		                <div class="layui-input-block">
		                    <input type="text" name="adminMsg" required lay-verify="required" value="{{d.rowdata.adminMsg}}" placeholder="请输入角色描述" autocomplete="off" class="layui-input">
		                </div>
		            </div>
					<div class="layui-form-item">
    					<label class="layui-form-label">角色权限</label>
    					<div class="layui-input-block" id="findJs"></div>
  					</div>
					<div class="layui-form-item layui-upload ">
  		  				<label class="layui-form-label">头像</label>
						<div class="layui-upload layui-input-block">
		  					<button type="button" class="layui-btn layui-btn-primary" id="fileBtn"><i class="layui-icon">&#xe67c;</i>{{d.rowdata.msg}}</button>
		  					<div class="layui-upload-list" style="display: none">
		    					<img class="layui-upload-img" id="pic" src="../../{{d.rowdata.adminPictrue}}" style="width: 100px;height: 100px">
		    					<p id="errorText"></p>
		  					</div>
						</div>
					</div>
		            <div class="layui-form-item" style="display:none;">
		                <div class="layui-input-block">
		                    <button class="layui-btn" lay-submit lay-filter="formEdit">立即提交</button>
		                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
		                </div>
		            </div>
		        </form>
		    </div>
		</script>
	    <script src="../../res/js/common/jquery-1.11.2.min.js"></script>       
	<script>
		//搜索框同步输入
		function lockInput(obj,id){
			$("#"+id).val($(obj).val());
		}
	</script>
	<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 --> 
	<script src="../../res/layui/layui.all.js"></script> 
	<script type="text/html" id="imgTpl">
		<img style="height:100%;height:30px;" src="../../{{d.adminPictrue}}">
    </script>
	<script>
		
		layui.use(['table','upload'], function(){
		  	var table = layui.table;
			  	$ = layui.jquery,
	            layer = layui.layer,
	            form = layui.form,
	            laytpl = layui.laytpl;
	        var tableIns = table.render({
		    	elem: '#demo'
		    	,height: 'full-50' //容器高度
		    	,url:'../../admin/findAll.action'
		    	,page: true
		    	,id: 'demo'
		    	,cols: [[
		      		{checkbox: true,fixed: true}
			      ,{field:'adminId', width:180, title: 'ID', align: 'center'}
			      ,{field:'comName', title: '公司名称',align: 'center'}
			      ,{field:'adminName', width:110, title: '用户名', align: 'center'}
			      ,{field:'adminMsg', width:200, title: '角色描述', align: 'center'}
			      ,{field:'adminPictrue', title: '头像', width: 80,align: 'center',templet:'#imgTpl'}
			      ,{fixed: 'right',title: '操作',width: 160,align: 'center',toolbar: '#barDemo'}
			    ]],
	            loading: true
	        });
	        
	      	//查询类型下拉框数据
	        var staticData = null;
	        $.ajax({ url:"../../company/findAll.action",
                type:'post',//method请求方式，get或者post
                cache: false,//同步
                dataType:'json',//预期服务器返回的数据类型
                success:function(mes){//res为相应体,function为回调函数
                	//增加及修改类型下拉框内的数据
                	staticData = mes;
                	//循环添加类型搜索框内的数据
                	$.each(mes.types,function(index,item){
                		$("#drug-type").append("<option value="+item.comId+">"+item.comName+"</option>");
                	});
                	//渲染类型搜索框内的下拉框
                	renderForm();
                }
             });
	        //监听搜索表单提交
	        form.on('submit(search)', function(data) { 
	            //带条件查询
	            tableIns.reload({
	                where: data.field
	            });
	            $('.kit-search-mored').hide();
	            return false;
	        });
	      	//渲染 修改和增加弹出层
		    function showlayer(d){
		    	laytpl($('#edit-tpl').html()).render(d,function(html) {
                    layer.open({
                        type: 1,
                        title: '表单',
                        content: html,
                        area: ['800px', '430px'],
                        btn: ['提交', '重置', '取消'],
                        yes: function(index, layero) {
                            editIndex = index;
                            $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
                        },
                        btn2: function(index, layero) {
                            $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
                            return false;
                        },
                        success: function() {
                            form.render(null, 'form-edit');
                        }
                    });
                    //查询角色数据
        	        $.ajax({ url:"../../role/queryList.action",
                        type:'post',//method请求方式，get或者post
                        async: false,//同步
                        dataType:'json',//预期服务器返回的数据类型
                        success:function(mes){//res为相应体,function为回调函数
                        	//循环添加角色的数据
                        	$.each(mes.data,function(index,item){
                        		$("#findJs").append('<input type="checkbox" class="check" lay-filter="encrypt" value="'+item.roleId+'" name="mul" title="'+item.roleName+'">');
                        		renderForm();
                        	});
                         }
                     });
                    upload();
                });
		    }
	      	
		    //监听工具条按钮点击
	        table.on('tool(demo)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
	            var data = obj.data; //获得当前行数据
	            var layEvent = obj.event; //获得 lay-event 对应的值
	            var tr = obj.tr; //获得当前行 tr 的DOM对象
	
	            if (layEvent === 'detail') { //查看
	            	maxlayer();
	                console.log(table.checkStatus('demo'));
	            } else if (layEvent === 'del') { //删除
	                layer.confirm('真的删除行么', function(index) {
	                	layer.close(index);
	                    update("../../admin/delete.action",{"adminId":data.adminId,"isva":"0"});
	                });
	            } else if (layEvent === 'edit') { //编辑
	            	data["msg"]="更改图片";
	            	var d = {
 	                	rowdata: data,
 	                	types: staticData.data
 	                };
	            	showlayer(d);
	            	$(".layui-upload-list").css("display", "block");
	            	 
	            	 //查询角色数据
        	        $.ajax({ url:"../../admin/findByRole.action",
        	        	data:{"adminId":data.adminId},
                        type:'post',//method请求方式，get或者post
                       
                        dataType:'json',//预期服务器返回的数据类型
                        success:function(mes){//res为相应体,function为回调函数
                        	//循环添加角色的数据
                        	$.each(mes,function(index,item){
                        		$("input[name='mul']").each(function(){ 
                            		if ($(this).val() == item.roleId) {
                            			$(this).prop("checked",true);
                            			var str = "";
                    	      			str+=item.roleId+"@";
                    	      			$("#roid").val($("#roid").val()+str);
                            		} 
                        		});
                        		renderForm();
                        	});
                         }
                     });
	            }
	        });
	      	
	        //表单渲染
	        form.render(null, 'kit-search-form');
	        //更多筛选点击事件
	        $('#kit-search-more').on('click', function() {
	            $('.kit-search-mored').toggle();
	        });
	        
	        
	        
	        form.on('checkbox(encrypt)', function(data){
	        	if(data.elem.checked == true) {
	      			var str = "";
	      			str+=data.value+"@";
	      			$("#roid").val($("#roid").val()+str);
	      		} else {
	      			 //取得文本框的值
	    			 var aa = $("#roid").val();
	    			 //把文本框清空
	    			 $("#roid").val("")
	    			 //文本框的值按取消复选框的id来去除
	    			 var bb = aa.replace(data.value+"@",'');
	    			 //把值重新赋给文本框
	    			 $("#roid").val(bb);
	      		}

	        });
	        
	        
	        var editIndex;
	        
	        //增加和修改弹出层   提交按钮点击事件
	        form.on('submit(formEdit)', function(data) {
	        	
            	if ($("[name=adminPictrue]").val()=="") {
            		layer.msg('未上传文件');
                	$("#fileBtn").html('<span style="color:red"><i class="layui-icon">&#xe67c;</i>选择文件</span>');
                	form.render(null, 'form-edit');
                	return false;
                }
            	update("../../admin/addAdmin.action",data.field);
            	if (close) editIndex && layer.close(editIndex); //关闭弹出层
            	return false;
	        });
	        
	      	//增加、批量删除 按钮点击事件
	        $('.kit-search-btns').children('a').off('click').on('click', function() {
	            var $that = $(this),
	                action = $that.data('action');
	            switch (action) {
	            	//点击的是 增加按钮
	                case 'add':
	                    var d = {
	                		//替换增加页面文本框内出现的undefine
	                        rowdata: {
	                        	adminId: '',adminName: '',adminPwd: '',adminPictrue: '',adminMsg: '',isva:1,isva:'0',optime:'',oper:'',sort:'',msg: '选择图片'
	                        },
	                      	//类型下拉框数据
	                        types: staticData.data
	                    };
	                    showlayer(d);
	                    break;
	                    
	                //点击的是 批量删除按钮
	                case 'del-bulk':
	                    var d = table.checkStatus('demo');
	                    if (d.data.length === 0) {
	                        layer.msg('请选择要删除的数据');
	                        return;
	                    }
	                    var data = d.data,
	                        names = [],
	                        ids = [];
	                    layui.each(data, function(index, item) {
	                        names.push(item.adminName);
	                        ids.push(item.adminId);
	                    });
	                    layer.confirm('真的删除行么', function(index) {
	                    	layer.close(index);
	                    	update("../../admin/bulkUpdate.action",ids);
		                });
	                    break;
	            }
	        });
		});
		
		//全屏弹窗
		function maxlayer(){
			var index = layer.open({
			  type: 2,
			  title: '管理员弹窗',
			  content: 'https://www.baidu.com',
			  area: ['800px', '430px']
			  //maxmin: true
			});
			layer.full(index);
		}
		
		//增加、修改、删除、批量删除 都是用的这一个方法
	    function update(url,data){
	    	$.ajax({
	    		url: url,
                type:'post',//method请求方式，get或者post
                cache: false,//同步
                dataType:'json',//预期服务器返回的数据类型
                data: JSON.stringify(data),//表格数据序列化
                contentType: "application/json; charset=utf-8",
                success:function(mes){//res为相应体,function为回调函数
                	$(".layui-laypage-btn")[0].click();//当前表格刷新
                    if(mes.status==1){ 
                    	var close = true;//有弹出层时是关闭弹出层 false不关闭
                        $("#res").click();//调用重置按钮将表单数据清空
                    }
                    layer.msg(mes.msg);
                },
               	error:function(){layer.alert('数据异常，请稍后重试！！！',{icon:5});}
             });
	    }
		
		
	  	//上传文件
	    function upload(){
	    	layui.upload.render({
                elem: '#fileBtn'
                ,url: '../../admin/upload.action'
                ,accept: 'file'
                ,auto: false
                ,bindAction: '#uploadBtn'
                ,before: function(){
                	layer.load(2,{shade:false});
                }
                ,done: function(res){
                	layer.closeAll("loading");
                	layer.msg(res.msg);
                	if (res.status=="1") {
                		 $("[name=adminPictrue]").val(res.obj);
                		 $("#fileBtn").html('<i class="layui-icon">&#xe67c;</i>选择文件');
                		 form.render('form-edit');
                	}
                }
            });
	    }
	  	
	  	//上传文件
	    function uploads(){
	    	//普通图片上传
	        var uploadInst = layui.upload.render({
	          elem: '#fileBtn'
	          ,url: '../../admin/upload.action'
	          ,before: function(obj){
	        	layer.load(2,{shade:false});
	            //预读本地文件示例，不支持ie8
	            obj.preview(function(index, file, result){
	            	$(".layui-upload-list").css("display", "block");
	                $('#pic').attr('src', result); //图片链接（base64）
	            });
	          }
	          ,done: function(res){
	        	layer.closeAll("loading"); 
	            //如果上传失败
	            if(res.code > 0){
	              return layer.msg('上传失败');
	            }
	            //上传成功
	            $("input[name=drugPictrue]").val(res.obj);
	            $(".layui-upload-list").css("display", "block");
           		$("#fileBtn").html('<i class="layui-icon">&#xe67c;</i>更改图片');
           		layui.form.render('form-edit');
	          }
	          ,error: function(){
	        	layer.closeAll("loading"); 
	            //演示失败状态，并实现重传
	            var demoText = $('#errorText');
	            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
	            demoText.find('.demo-reload').on('click', function(){
	              uploadInst.upload();
	            });
	          }
	        });
	    }
		
	    //重新渲染表单
	  	function renderForm(){ 
  			layui.use('form', function(){ 
	  			var form = layui.form;//高版本建议把括号去掉，有的低版本，需要加() 
	  			form.render(); 
  			}); 
  		}
	  	
		//ajax加载动画
	    $(function () {
            $.ajaxSetup({
                layerIndex:-1,
                beforeSend: function () {
                    this.layerIndex = layer.load(1, { shade: [0.8, '#ffffff'] });
                },
                complete: function () {
                    layer.close(this.layerIndex);
                },
                error: function () {
                    layer.alert('部分数据加载失败，可能会导致页面显示异常，请刷新后重试', {
                        skin: 'layui-layer-molv'
                       , closeBtn: 0
                       , shift: 4 //动画类型
                    });
                }
            });
        });
	</script>
</body>
</html>